package com.fengwei;

import com.fengwei.util.SpringContextUtil;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11Nio2Protocol;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@MapperScan("com.fengwei.*")
public class MdmsAdminApplication {

    private final static Logger logger = LoggerFactory.getLogger(MdmsAdminApplication.class);

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(MdmsAdminApplication.class, args);
        SpringContextUtil.setApplicationContext(context);
        String startInfo = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date())
                + "MdmsAdminApplication started!";
        logger.info(startInfo);
        System.out.println(startInfo);
    }

    @Autowired
    private Environment env;

    /**
     * http的bean
     * 只有配置文件配置了http.ifopen=true，才会加载这个bean
     * https肯定会启用，然后http必须配置上述的才启用
     *
     * @return
     */
    @Bean
    @ConditionalOnExpression("#{'true'.equals(environment['http.ifopen'])}")
    public ServletWebServerFactory servletContainer() {
        logger.debug("http will open...");
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        // 添加http
        final Connector connector = new Connector("org.apache.coyote.http11.Http11Nio2Protocol");
        connector.setPort(env.getProperty("http.port", Integer.TYPE));

        Http11Nio2Protocol protocol = (Http11Nio2Protocol) connector.getProtocolHandler();
        protocol.setConnectionTimeout(200);
        protocol.setMaxThreads(1000);
        protocol.setMaxConnections(500);

        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }

    @Bean
    public Map springSecurityUserTypeMap() {
        return new HashMap();
    }

}
